import random

from django.http import HttpResponse, JsonResponse
from django.views import View
from django_redis import get_redis_connection

from meiduo.libs.captcha.captcha import captcha
import logging

logger = logging.getLogger('django')


class ImageCodeView(View):

    def get(self, request, uuid):
        text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('image_%s' % uuid, 60, text)
        return HttpResponse(image,
                            content_type='image/jpg')


class SMSCodeView(View):

    def get(self, request, mobile):
        redis_conn = get_redis_connection('verify_code')
        flog = redis_conn.get('flog_%s' % mobile)
        if flog:
            return JsonResponse({'code': 400,
                                 'errmsg': '60秒内不要重复获取验证码'})
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        if not all([image_code_client, uuid]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})
        try:
            image_code_server = redis_conn.get('image_%s' % uuid)
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '获取数据失败'})
        if not image_code_server:
            return JsonResponse({'code': 400,
                                 'errmsg': '图形验证码已失效'})
        if image_code_client.lower() != image_code_server.decode().lower():
            return JsonResponse({'code': 400,
                                 'errmsg': '验证码输入错误'})
        try:

            redis_conn.delete('image_%s' % uuid)
        except Exception as e:
            # 日志的使用
            logger.error(e)
        sms_code = '%06d' % random.randint(0, 999999)
        # logger.info(sms_code)
        print(sms_code)
        pl = redis_conn.pipeline()

        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('flog_%s' % mobile, 60, 1)
        pl.excute()
        return JsonResponse({'code': 0,
                             'errmsg': '发送短信成功'})
